﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Codes {
    public partial class MainForm : Form {
        public MainForm() {
            InitializeComponent();
        }

        List<int> countLines(string[] extensions, string folderPath) {

            //初始化统计数组
            List<int> counts = new List<int>();
            for (int i = 0; i < extensions.Length; i++)
            {
                counts.Add(0);
            }

            //遍历文件夹进行统计
            DirectoryInfo rootFolder = new DirectoryInfo(folderPath);
            List<DirectoryInfo> folders = new List<DirectoryInfo>();

            folders.Add(rootFolder);
            int index = 0;
            while(index != folders.Count)
            {
                DirectoryInfo folder = folders[index];

                foreach (DirectoryInfo tempFolder in folder.GetDirectories()) {
                    folders.Add(tempFolder);
                }

                FileInfo[] files = folder.GetFiles();

                foreach (FileInfo file in files)
                {
                    for (int i = 0; i < extensions.Length; i++)
                    {
                        if (extensions[i].Equals(file.Extension))
                        {
                            int lines = 0;
                            StreamReader read = file.OpenText();
                            while (null != read.ReadLine()) {
                                lines++;
                            }
                            counts[i] += lines;
                        }
                    }
                }
                index++;
            }
            return counts;
        }

        private void chooseDirButt_Click(object sender, EventArgs e)
        {
            //选择文件夹
            FolderBrowserDialog folderDlg = new FolderBrowserDialog();
            folderDlg.ShowDialog();
            this.dirPathLabel.Text = folderDlg.SelectedPath;
            startButt.Enabled = true;
        }

        private void startButt_Click(object sender, EventArgs e) {
            if (this.dirPathLabel.Text.Equals("") || this.dirPathLabel.Text==null) {
                result.Text = "警告：请选择路径";
            } else {
                //清空输出框
                result.Text = "";

                //获得后缀名类型
                string[] extensions = this.extensions.Text.Split();

                List<int> count = countLines(extensions, this.dirPathLabel.Text);

                for (int i = 0; i < count.Count; i++) {
                    result.Text += "*" + extensions[i] + ":" + count[i] + "\r\n";
                }
            }
        }
    }
}
